import Vue from 'vue'
import Vuex, { Store } from 'vuex'

Vue.use(Vuex)

export default new Store({
  state: {
    count: 1,
    cart: JSON.parse(localStorage.getItem('cart') || '[]')
  },
  mutations: {
    // 添加购物车
    addCart (state, goodsinfo) {
      var flag = false
      state.cart.some(item => {
        if (item.id === goodsinfo.id) {
          item.count += goodsinfo.count
          flag = true
        }
      })

      if (!flag) {
        state.cart.push(goodsinfo)
      }
      localStorage.setItem('cart', JSON.stringify(state.cart))
    }
  },
  actions: {
    addCart ({ commit }, goodsinfo) {
      commit('addCart', goodsinfo)
    }
  },
  getters: {
    // 计算所有的数量
    getAllCount (state) {
      console.log(state)
      var c = 0
      state.cart.some(item => {
        c += item.count
      })
      console.log(c)
      return c
    },
    getAllPrice (state) {
      var totlaPrice = 0
      state.cart.some(item => {
        if (item.selected === true) {
          totlaPrice += item.sell_price * item.count
        }
      })
      return totlaPrice * 100
    }
  }
})
